package com.xls.commonlibrary.update;

import static com.xls.commonlibrary.wxapi.ConstWx.KEY_WX_UNION_ID;

import android.annotation.SuppressLint;
import android.webkit.ValueCallback;

import androidx.appcompat.app.AppCompatActivity;

import com.hjq.toast.Toaster;
import com.xls.commonlibrary.bean.UpdateVersionResult;
import com.xls.commonlibrary.http.Api;
import com.xls.commonlibrary.http.RetrofitHelper;
import com.xls.commonlibrary.http.RxLifecycle;
import com.xls.commonlibrary.http.Transformer;
import com.xls.commonlibrary.util.MMKVUtil;
import com.xls.commonlibrary.util.SysDataUtil;
import com.xls.commonlibrary.util.VersionCodeUtil;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Nonnull;

// [3]  第三步   后台检查渠道，更新信息，返回是否可以更新以及渠道包的apk信息like update接口
public class YxqdUtil {
    private static volatile YxqdUtil singleton = null;

    private YxqdUtil() {
    }

    public static YxqdUtil getInstance() {
        if (singleton == null) {
            synchronized (YxqdUtil.class) {
                if (singleton == null) {
                    singleton = new YxqdUtil();
                }
            }
        }
        return singleton;
    }


    ////////////////////////////////////////////////////

    @SuppressLint("CheckResult")
    public void checkUpdateChannel(
            @Nonnull AppCompatActivity activity,
            @Nonnull ValueCallback<UpdateVersionResult> callback
    ) {

        Map<String, String> p = new HashMap<>();

        p.put("unionId", MMKVUtil.getInstance().getKV().decodeString(KEY_WX_UNION_ID, ""));
        p.put("packageName", SysDataUtil.getInstance().getPkName());
        p.put("versionCode", VersionCodeUtil.getVersionCode() + "");
        p.put("versionName", VersionCodeUtil.getVersionName() );


        RetrofitHelper.getInstance().create(Api.class)
                .yxqdDownload(p)
                .compose(Transformer.transform())
                .compose(RxLifecycle.bindRxLifecycle(activity))
                .subscribe(
                        result -> {
                            if (result.getCode() == 1) {

                                if (callback != null) {
//                                    callback.onReceiveValue(result.getData());
                                }

                            } else {

                                Toaster.show(result.getMsg());

                            }
                        },
                        throwable -> {

                        }
                );
    }

}
